package com.itheima.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/registerServlet")
public class RegisterServlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 接收用户对象
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 封装用户数据
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        // 2. 调用Mapper, 根据用户名查询用户对象
        // 2.1 获取SQLSessionFactory对象
//        String resource = "mybatis-config.xml";
//        InputStream inputStream = Resources.getResourceAsStream(resource);
//        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

        // 2.2 获取SQLSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 2.3 获取Mapper对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        // 2.4 调用方法
        User u = mapper.selectByUsername(username);

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        // 3. 判断用户是否存在
        if (u == null){
            // 用户不存在
            mapper.add(user);
            // 提交事务
            sqlSession.commit();
            writer.write("注册成功～～～");
            // 释放资源
            sqlSession.close();

        }else {
            // 用户存在，给出提示
            writer.write("用户名己存在！");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}